package com.steak.stock.execute;

import com.alibaba.fastjson.JSON;
import com.steak.common.domain.dataobject.tcc.FreezeStock;
import com.steak.common.domain.dataobject.tcc.Stock;
import com.steak.common.domain.dto.StockDTO;
import com.steak.common.domain.dto.UpdateStockDTO;
import com.steak.common.result.Response;
import lombok.AllArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author 刘牌
 * @Title:
 * @date 2022/3/116:39
 */
@Component
@AllArgsConstructor
public class StockExecute {

    private final JdbcTemplate jdbcTemplate;

    public Response execute(StockDTO stock) throws InterruptedException {
        String sql = "UPDATE stock SET stock_num = ( SELECT sto.stock_num FROM ( SELECT ( st.stock_num - "+stock.getCount()+" ) stock_num FROM stock st WHERE st.commodity_id = "+stock.getCommodityId()+" ) sto) WHERE commodity_id = "+stock.getCommodityId()+"";
        jdbcTemplate.update(sql);
        return new Response(200,"increase stock success",null);
    }

    public FreezeStock queryByUserId(Integer userId) {
        String sql = "SELECT * FROM freeze_stock WHERE user_id = "+userId+"";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        System.out.println("freeze  "+maps);
        FreezeStock freezeStock;
        if (maps.size() == 0) freezeStock = null;
        else freezeStock = JSON.parseObject(JSON.toJSONString(maps.get(0)), FreezeStock.class);
        return freezeStock;
    }

    public Response saveFreezeStock(FreezeStock freezeStock) {
        String sql = "INSERT INTO freeze_stock(user_id , commodity_id , freeze_stock_num) VALUES("+freezeStock.getUserId()+","+freezeStock.getCommodityId()+","+freezeStock.getFreezeStock()+")";
        jdbcTemplate.execute(sql);
        return new Response(200,"saveFreezeStock success",null);
    }

    public Response deleteFreezeRecordByUserId(Integer userId) {
        String sql = "delete from freeze_stock WHERE user_id = "+userId+"";
        jdbcTemplate.execute(sql);
        return new Response(200,"delete freeze record success",null);
    }

    public Response updateStockNumByUserId(UpdateStockDTO updateStockDTO) {
        String sql = "UPDATE stock SET stock_num = ( SELECT sto.stock_num FROM ( SELECT ( st.stock_num + "+updateStockDTO.getCount()+" ) stock_num FROM stock st WHERE st.commodity_id = "+updateStockDTO.getCommodityId()+" ) sto) WHERE commodity_id = "+updateStockDTO.getCommodityId()+"";
        jdbcTemplate.update(sql);
        return new Response(200,"update stock success",null);
    }
}
